package cn.hchaojie.boot.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import cn.hchaojie.boot.domain.Role;
import cn.hchaojie.boot.mapper.UserMapper;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private UserMapper mapper;
	
	// 告诉spring security，如何查找用户信息
	
	/// UserDetails: 封装了用户的信息，主要是用户名、密码、权限
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 把用户信息和角色信息都查出来
		cn.hchaojie.boot.domain.User user = mapper.getUserByName(username);
		
		List<Role> roles = user.getRoles();
		if (roles == null) {
			logger.error("用户角色为空，用户名为：{}", username);
			
			throw new RuntimeException("用户角色不能为空！");
		}
		
//		List<String> rolesName = new ArrayList<>();
//		for (Role r : roles) {
//			rolesName.add(r.getKeyword());
//		}
//		// admin, sales
//		String[] array = rolesName.toArray(new String[0]);
		
		String[] array = roles.stream()		// 将list集合变成流
			.map(r -> "ROLE_" + r.getKeyword())			// 映射 Role -> String
			.collect(Collectors.toList())	// 每个元素收集到list集合
			.toArray(new String[0]);		// list集合转换成数组
		
		 return User.builder()
				.username(username)
				.password(user.getPassword())
				.authorities(array)
				.build();
	}

}
